<template>
  <a-row :gutter="10">
    <a-col :md="12" :sm="24">
      <a-card :bordered="false">
        <!-- 查询区域-END -->
        <!-- 操作按钮区域 -->
        <div class="table-operator">
          <a-button
            @click="handleAdd(1)"
            type="primary"
            icon="plus"
            :disabled="isDisabledAuth('filesBusinessCategory:add')"
            >添加一级
          </a-button>
          <a-button @click="handleAdd(2)" type="primary">添加下级</a-button>

          <a-button
            type="primary"
            icon="download"
            @click="handleExportXls('业务分类')"
            :disabled="isDisabledAuth('filesBusinessCategory:export')"
            >导出
          </a-button>
          <a-upload
            name="file"
            :showUploadList="false"
            :multiple="false"
            :headers="tokenHeader"
            :action="importExcelUrl"
            @change="handleImportExcel"
          >
            <a-button type="primary" icon="import" :disabled="isDisabledAuth('filesBusinessCategory:import')"
              >导入
            </a-button>
          </a-upload>
          <!-- 高级查询区域 -->
          <!--<j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>-->
          <a-dropdown v-if="selectedRowKeys.length > 0">
            <a-menu slot="overlay">
              <!-- <a-menu-item key="1" @click="batchDel" :disabled="isDisabledAuth('filesBusinessCategory:delete')">
                <a-icon type="delete" />
                删除
              </a-menu-item> -->
            </a-menu>
            <a-button style="margin-left: 8px">
              批量操作
              <a-icon type="down" />
            </a-button>
          </a-dropdown>
          <a-popover title="自定义列" trigger="click" placement="leftBottom">
            <template slot="content">
              <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
                <a-row>
                  <template v-for="(item, index) in defColumns">
                    <template v-if="item.key != 'rowIndex' && item.dataIndex != 'action'">
                      <a-col :span="12" :key="index">
                        <a-checkbox :value="item.dataIndex">{{ item.title }}</a-checkbox>
                      </a-col>
                    </template>
                  </template>
                </a-row>
              </a-checkbox-group>
            </template>
            <a style="float: right">
              <a-icon type="setting" :style="iconStyle" />
            </a>
          </a-popover>
        </div>

        <!-- table区域-begin -->
        <div style="background: #fff; padding-left: 16px; height: 100%; margin-top: 5px">
          <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
            <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
            <a style="font-weight: 600">{{ checkedKeys.length }}</a
            >项
            <a style="margin-left: 24px" @click="onClearSelected">清空</a>
          </div>
          <a-input-search @search="onSearch" style="width: 100%; margin-top: 10px" placeholder="请输入业务类别名称" />
          <a-col :md="10" :sm="24">
            <template>
              <a-dropdown :trigger="[this.dropTrigger]" @visibleChange="dropStatus">
                <span style="user-select: none">
                  <a-tree
                    checkable
                    multiple
                    @select="onSelect"
                    @check="onCheck"
                    @rightClick="rightHandle"
                    :selectedKeys="selectedKeys"
                    :checkedKeys="checkedKeys"
                    :treeData="categoryTree"
                    :checkStrictly="checkStrictly"
                    :expandedKeys="iExpandedKeys"
                    :autoExpandParent="autoExpandParent"
                    @expand="onExpand"
                  >
                    <span slot="title" slot-scope="value" :style="value.status && value.status == 'disabled' ? 'color: #c8c9cc' : ''">{{ value.title }}</span>
                  </a-tree>
                </span>
                <!--新增右键点击事件,和增加添加和删除功能-->
                <a-menu slot="overlay">
                  <a-menu-item @click="handleAdd(3)" key="1">添加</a-menu-item>
                  <!-- <a-menu-item @click="handleDelete" key="2">删除</a-menu-item> -->
                  <a-menu-item @click="closeDrop" key="3">取消</a-menu-item>
                </a-menu>
              </a-dropdown>
            </template>
          </a-col>
        </div>
      </a-card>
      <!---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------>
      <div class="drawer-bootom-button">
        <a-dropdown :trigger="['click']" placement="topCenter">
          <a-menu slot="overlay">
            <a-menu-item key="1" @click="switchCheckStrictly(1)">父子关联</a-menu-item>
            <a-menu-item key="2" @click="switchCheckStrictly(2)">取消关联</a-menu-item>
            <a-menu-item key="3" @click="checkALL">全部勾选</a-menu-item>
            <a-menu-item key="4" @click="cancelCheckALL">取消全选</a-menu-item>
            <a-menu-item key="5" @click="expandAll">展开所有</a-menu-item>
            <a-menu-item key="6" @click="closeAll">合并所有</a-menu-item>
          </a-menu>
          <a-button>
            树操作
            <a-icon type="up" />
          </a-button>
        </a-dropdown>
      </div>
      <!---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------>
    </a-col>
    <a-col :md="12" :sm="24">
      <a-card :bordered="false" v-if="selectedKeys.length > 0">
        <a-spin :spinning="confirmLoading">
          <j-form-container :disabled="false">
            <a-form-model :form="form" ref="form" :model="model" :rules="validatorRules" slot="detail">
              <a-row :gutter="48">
                <a-col :span="12">
                  <a-form-model-item label="编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="categoryCode">
                    <a-input v-model="model.categoryCode" placeholder="请输入编号" disabled></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item label="创建日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
                    <j-date
                      placeholder="请选择日期"
                      v-model="model.createTime"
                      :show-time="true"
                      date-format="YYYY-MM-DD HH:mm"
                      style="width: 100%"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item label="经办人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposer">
                    <select-person-input v-model="model.proposer" disabled />
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="经办部门"
                    prop="proposerDeptId"
                  >
                    <j-select-depart :disabled="formDisabled" v-model="model.proposerDeptId" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item label="名称" prop="categoryName">
                    <a-input :disabled="formDisabled" v-model="model.categoryName" placeholder="请输入名称"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item label="业务分类类型" prop="businessType">
                    <j-dict-select-tag
                      :disabled="formDisabled"
                      v-model="model.businessType"
                      dictCode="business_type"
                      placeholder="请选择"/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item label="审批人" prop="approvalUser">
                    <select-user-by-dep
                      :disabled="formDisabled"
                      :multi="false"
                      v-model="model.approvalUser"
                      placeholder="请选择审批人"
                    ></select-user-by-dep>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12" v-if="isDisableParent">
                  <a-form-model-item label="上级分类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="parentId">
                    <j-dict-select-tag
                      :disabled="formDisabled"
                      type="list"
                      v-model="model.parentId"
                      dictCode="erp_files_business_category,category_name,id"
                      placeholder="请选择上级分类编码"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item label="分类等级" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="level">
                    <j-dict-select-tag
                      :disabled="formDisabled"
                      type="list"
                      v-model="model.level"
                      dictCode="business_category_level"
                      placeholder="请选择分类等级"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="12" v-if="!isDisableParent">
                  <a-form-model-item
                    label="负责人岗位"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="leaderPostCode"
                  >
                    <j-search-select
                      :disabled="formDisabled"
                      v-model="model.leaderPostCode"
                      dict="sys_position,name,code,del_flag = 0 and audit_status=2"
                      placeholder="请选择岗位"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="标准工时(人/天)"
                    prop="standardHours"
                  >
                    <a-input-number
                      style="width: 100%;"
                      step="0.1"
                      :precision=1
                      :disabled="formDisabled"
                      v-model="model.standardHours"
                      placeholder="请输入标准工时"
                    ></a-input-number>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="status">
                    <j-dict-select-tag
                      :disabled="formDisabled"
                      type="radio"
                      v-model="model.status"
                      dictCode="ENABLE_OR_DISABLE"
                      placeholder="请选择状态"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="24">
                  <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                    <a-textarea :disabled="formDisabled" v-model="model.remark" rows="4" placeholder="请输入备注" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="24">
                  <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" style="float: right">
                    <a-button
                      @click="emptyCurrForm"
                      type="default"
                      htmlType="button"
                      icon="sync"
                      style="margin-right: 10px"
                      >重置</a-button
                    >
                    <a-button @click="submitCurrForm" type="primary" htmlType="button" icon="form">保存</a-button>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
          </j-form-container>
        </a-spin>
      </a-card>
      <a-card v-else>
        <a-empty>
          <span slot="description"> 请先选择一个业务分类! </span>
        </a-empty>
      </a-card>
    </a-col>
    <erp-files-business-category-modal ref="modalForm" @ok="modalFormOk"></erp-files-business-category-modal>
  </a-row>
</template>

<script>
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import '@/assets/less/TableExpand.less'
import pick from 'lodash.pick'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import ErpFilesBusinessCategoryModal from './modules/ErpFilesBusinessCategoryModal'
import { DisabledAuthFilterMixin } from '@/mixins/DisabledAuthFilterMixin'
import { deleteAction, getAction, httpAction } from '@api/manage'
import { mapGetters } from 'vuex'
import SelectPersonInput from '@/views/scy/components/SelectPersonInput'
import JSearchSelect from '@/views/scy/components/JSearchSelect.vue'
const queryCategoryTreeList = (params) =>
  getAction('/api/erp/files/category/filesBusinessCategory/queryTreeList', params)
const deleteByCategoryId = (params) => deleteAction('/api/erp/files/category/filesBusinessCategory/delete', params)
const searchByKeywords = (params) => getAction('/api/erp/files/category/filesBusinessCategory/searchBy', params)
export default {
  name: 'FilesBusinessCategoryList',
  mixins: [JeecgListMixin, mixinDevice, DisabledAuthFilterMixin],
  components: {
    SelectUserByDep,
    ErpFilesBusinessCategoryModal,
    SelectPersonInput,
    JSearchSelect,
  },
  data() {
    return {
      model: {
        categoryName: '',
        categoryCode: '',
      },
      description: '业务分类管理页面',
      // 表头
      columns: [],
      confirmLoading: false,
      form: this.$form.createForm(this),
      settingColumns: [],
      checkedKeys: [],
      selectedKeys: [],
      categoryTree: [],
      iExpandedKeys: [],
      currSelected: {},
      checkStrictly: true,
      autoExpandParent: true,
      isDisableParent: false,
      dropTrigger: '',
      categoryLevelDictCode: 'erp_files_business_category,category_code,category_code',
      labelCol: {},
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 },
      },
      // 列设置
      // 列定义
      defColumns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '名称',
          align: 'center',
          dataIndex: 'categoryName',
        },
        {
          title: '编码',
          align: 'center',
          dataIndex: 'categoryCode',
        },
        {
          title: '上级分类',
          align: 'center',
          dataIndex: 'parentId_dictText',
        },
        {
          title: '分类等级',
          align: 'center',
          dataIndex: 'level_dictText',
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'status_dictText',
        },
        {
          title: '备注',
          align: 'center',
          dataIndex: 'remark',
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action',
          },
        },
      ],
      validatorRules: {
        categoryName: [{ required: true, message: '请输入名称!' }],
        categoryCode: [{ required: true, message: '请输入编码!' }],
        parentId: [{ required: false, message: '请输入上级分类!' }],
        level: [{ required: true, message: '请输入分类等级!' }],
        status: [{ required: true, message: '请输入状态!' }],
        businessType: [{ required: true, message: '请输入业务类型!' }],
      },
      url: {
        list: '/api/erp/files/category/filesBusinessCategory/list',
        edit: '/api/erp/files/category/filesBusinessCategory/edit',
        delete: '/api/erp/files/category/filesBusinessCategory/delete',
        deleteBatch: '/api/erp/files/category/filesBusinessCategory/deleteBatch',
        exportXlsUrl: '/api/erp/files/category/filesBusinessCategory/exportXls',
        importExcelUrl: 'api/erp/files/category/filesBusinessCategory/importExcel',
      },
      dictOptions: {},
      superFieldList: [],
    }
  },
  created() {
    this.getSuperFieldList()
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
    formDisabled() {
      return this.disabled
    },
  },
  methods: {
    ...mapGetters(['userInfo']),
    expandAll() {
      this.iExpandedKeys = this.allTreeKeys
    },
    closeAll() {
      this.iExpandedKeys = []
    },
    checkALL() {
      this.checkStriccheckStrictlytly = false
      this.checkedKeys = this.allTreeKeys
    },
    cancelCheckALL() {
      // this.checkedKeys = this.defaultCheckedKeys
      this.checkedKeys = []
    },
    switchCheckStrictly(v) {
      if (v == 1) {
        this.checkStrictly = false
      } else if (v == 2) {
        this.checkStrictly = true
      }
    },
    submitCurrForm() {
      this.$refs.form.validate((valid, values) => {
        if (valid) {
          let formData = Object.assign(this.currSelected, values)
          console.log('formData', formData)
          console.log('Received values of form: ', formData)
          httpAction(this.url.edit, formData, 'put').then((res) => {
            if (res.success) {
              this.$message.success('保存成功!')
              this.loadTree()
            } else {
              this.$message.error(res.message)
            }
          })
        } else {
          if (!this.currSelected.id) {
            this.$message.warning('请点击选择要修改分类!')
            return false
          }
        }
      })
    },
    emptyCurrForm() {
      this.$set(this.model, 'categoryName', null)
      this.$set(this.model, 'remark', null)
    },
    nodeSettingFormSubmit() {
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)
        }
      })
    },
    handleAdd(num) {
      if (num == 1) {
        this.$refs.modalForm.add()
        this.$refs.modalForm.title = '新增'
      } else if (num == 2) {
        let key = this.currSelected.key
        if (!key) {
          this.$message.warning('请先点击选中上级分类！')
          return false
        }
        this.$refs.modalForm.add(this.currSelected)
        this.$refs.modalForm.title = '新增'
      } else {
        let record = this.categoryTree.find((val, index, arr) => val.id == this.rightClickSelectedKey)
        this.$refs.modalForm.add(record)
        this.$refs.modalForm.title = '新增'
      }
    },
    nodeModalOk() {
      this.loadTree()
    },
    nodeModalClose() {},
    batchDel: function () {
      console.log(this.checkedKeys)
      if (this.checkedKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
      } else {
        var ids = ''
        for (var a = 0; a < this.checkedKeys.length; a++) {
          ids += this.checkedKeys[a] + ','
        }
        var that = this
        this.$confirm({
          title: '确认删除',
          content: '确定要删除所选中的 ' + this.checkedKeys.length + ' 条数据，以及子节点数据吗?',
          onOk: function () {
            deleteAction(that.url.deleteBatch, { ids: ids }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadTree()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            })
          },
        })
      }
    },
    handleDelete() {
      var that = this
      this.$confirm({
        title: '确认删除',
        content: '确定要删除此业务分类以及子节点数据吗?',
        onOk: function () {
          deleteByCategoryId({ id: that.rightClickSelectedKey }).then((resp) => {
            if (resp.success) {
              // 删除成功后，去除已选中中的数据
              that.checkedKeys.splice(
                that.checkedKeys.findIndex((key) => key === that.rightClickSelectedKey),
                1
              )
              that.$message.success('删除成功!')
              that.loadTree()
              // 删除后同步清空右侧基本信息内容
              let categoryCode = that.form.getFieldValue('categoryCode')
              if (categoryCode && categoryCode === that.rightClickSelectedCategoryCode) {
                that.onClearSelected()
              }
            } else {
              that.$message.warning('删除失败!')
            }
          })
        },
      })
    },
    onSearch(value) {
      let that = this
      if (value) {
        searchByKeywords({ keyWord: value }).then((res) => {
          if (res.success) {
            that.categoryTree = []
            for (let i = 0; i < res.result.length; i++) {
              let temp = res.result[i]
              that.categoryTree.push(temp)
            }
          } else {
            that.$message.warning(res.message)
          }
        })
      } else {
        that.loadTree()
      }
    },
    onClearSelected() {
      this.hiding = true
      this.checkedKeys = []
      this.currSelected = {}
      this.form.resetFields()
      this.selectedKeys = []
    },
    // 右键点击下拉框改变事件
    dropStatus(visible) {
      if (visible == false) {
        this.dropTrigger = ''
      }
    },
    // 右键店家下拉关闭下拉框
    closeDrop() {
      this.dropTrigger = ''
    },
    loadData() {
      this.refresh()
    },
    loadTree() {
      var that = this
      that.treeData = []
      that.categoryTree = []
      queryCategoryTreeList({ status: 'all' }).then((res) => {
        if (res.success) {
          // 分类全选后，再添加分类，选中数量增多
          this.allTreeKeys = []
          for (let i = 0; i < res.result.length; i++) {
            let temp = res.result[i]
            that.treeData.push(temp)
            that.categoryTree.push(temp)
            that.setThisExpandedKeys(temp)
            that.getAllKeys(temp)
            // console.log(temp.id)
          }
          this.loading = false
        }
      })
    },
    getAllKeys(node) {
      this.allTreeKeys.push(node.key)
      if (node.children && node.children.length > 0) {
        for (let a = 0; a < node.children.length; a++) {
          this.getAllKeys(node.children[a])
        }
      }
    },
    setThisExpandedKeys(node) {
      if (node.children && node.children.length > 0) {
        this.iExpandedKeys.push(node.key)
        for (let a = 0; a < node.children.length; a++) {
          this.setThisExpandedKeys(node.children[a])
        }
      }
    },
    refresh() {
      this.loading = true
      this.loadTree()
    },
    // 右键操作方法
    rightHandle(node) {
      this.dropTrigger = 'contextmenu'
      console.log(node.node.eventKey)
      this.rightClickSelectedKey = node.node.eventKey
      this.rightClickSelectedCategoryCode = node.node.dataRef.categoryCode
    },
    onExpand(expandedKeys) {
      console.log('onExpand', expandedKeys)
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.iExpandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onCheck(checkedKeys, info) {
      this.hiding = false
      // this.checkedKeys = checkedKeys.checked
      // <!---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------>
      if (this.checkStrictly) {
        this.checkedKeys = checkedKeys.checked
      } else {
        this.checkedKeys = checkedKeys
      }
      // <!---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------>
    },
    onSelect(selectedKeys, e) {
      this.showSelect = false
      this.hiding = false
      let record = e.node.dataRef
      console.log('onSelect-record', record)
      this.currSelected = Object.assign({}, record)
      this.model = this.currSelected
      if (this.model.level == '1') {
        this.isDisableParent = false
      } else {
        this.isDisableParent = true
      }
      this.selectedKeys = [record.key]
      this.model.parentId = record.parentId
      this.showSelect = true
      this.setValuesToForm(record)
    },
    // 触发onSelect事件时,为部门树右侧的form表单赋值
    setValuesToForm(record) {
      this.$nextTick(() => {
        this.form.getFieldDecorator('fax', { initialValue: '' })
        this.form.setFieldsValue(
          pick(
            record,
            'proposer',
            'proposer_dept_id',
            'handler_id',
            'handler_dept_id',
            'handler_dept_code',
            'create_time',
            'categoryName',
            'categoryCode',
            'parentId',
            'level',
            'status',
            'remark'
          )
        )
      })
    },
    initDictConfig() {},
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'categoryName', text: '名称', dictCode: '' })
      fieldList.push({ type: 'string', value: 'categoryCode', text: '编码', dictCode: '' })
      fieldList.push({
        type: 'sel_search',
        value: 'parentId',
        text: '上级分类',
        dictTable: 'erp_files_business_category',
        dictText: 'category_name',
        dictCode: 'id',
      })
      fieldList.push({ type: 'string', value: 'level', text: '分类等级', dictCode: '' })
      fieldList.push({ type: 'string', value: 'status', text: '状态', dictCode: 'ENABLE_OR_DISABLE' })
      fieldList.push({ type: 'Text', value: 'remark', text: '备注', dictCode: '' })
      this.superFieldList = fieldList
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
